
var express = require('express');
var router = express.Router();
const  VCODE =require("../config/code"); //错误码
/*自己的web页面*/
const  logger =  require("../cors/log").getLogger("selfweb");
const USER = require("../src/user");
/* GET home page. */
router.get('/login', function(req, res, next) {
    res.locals._app = '';
    res.locals._cd = '';
    res.render('login');
});
router.get('/register', function(req, res, next) {
    res.locals._app = '';
    res.locals._cd = '';
    res.render('register');
});

router.post('/api/login', function(req, res, next) {
    USER.signin(req.body).then(function (ret) {
        if( ret.data.type == VCODE.type.super){
            logger.info("后台管理登录: ip为"+ getIp(req)+";设备为:"+ getMachine(req));
            req.session.admin = ret.data;
            var data = Object.assign({data:{"_url":"/admin"}},VCODE.success);
            res.send(data);
        }else{
            res.send(VCODE.user);
        }
    }).catch(function (ret) {
        res.send(ret);
    })
});
router.post('/api/loginout', function(req, res, next) {
    req.session.admin = null;
    res.send(VCODE.success);
});





function getMachine(req) {
    var deviceAgent = req.headers["user-agent"].toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
    if (agentID) {
        return "Mobile";
    } else {
        return "PC";
    }
}
function getIp(req) {
    return (req.headers['x-forwarded-for'] || '').split(',')[0] || req.ip;
}


module.exports = router;
